package com.itheima.test.producer;

import org.apache.kafka.clients.producer.*;

import java.util.Properties;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;

/**
 * 生产者
 */
public class ProducerQuickStart100 {

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        //1.kafka的配置信息
        Properties properties = new Properties();
        //kafka的连接地址
        properties.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG,"192.168.200.130:9092");
        //发送失败，失败的重试次数
        properties.put(ProducerConfig.RETRIES_CONFIG,5);
        //消息key的序列化器
        properties.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG,"org.apache.kafka.common.serialization.StringSerializer");
        //消息value的序列化器
        properties.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG,"org.apache.kafka.common.serialization.StringSerializer");

        properties.put(ProducerConfig.ACKS_CONFIG, "all");
        //数据压缩
        properties.put(ProducerConfig.COMPRESSION_TYPE_CONFIG,"lz4");


        //2.生产者对象
        KafkaProducer<String,String> producer = new KafkaProducer<String, String>(properties);

      /*  for(int i=0;i<=20;i++){
            //封装发送的消息
            ProducerRecord<String,String> record = new ProducerRecord<String, String>("itheima-topic114-1","aaa","hello kafka itcast");

            //3.发送消息
            Future<RecordMetadata> send = producer.send(record);
            RecordMetadata recordMetadata = send.get();
            System.out.println(recordMetadata.partition());
            System.out.println(recordMetadata.topic());
            System.out.println(recordMetadata.offset());
            System.out.println("-------------------------");
            Thread.sleep(100);
        }*/



        //封装发送的消息
        //参数1 主题名称，   参数2是几号分区   参数3是消息的key    参数4消息的内容
        ProducerRecord<String,String> record = new ProducerRecord<String, String>("itheima-topic114-1",0, "aaa","hello kafka itcast0");


        //3.发送消息
        Future<RecordMetadata> send = producer.send(record);
        RecordMetadata recordMetadata = send.get();
        System.out.println("分区:"+recordMetadata.partition()+" topic"+recordMetadata.topic()+"   offset:"+recordMetadata.offset());
        Thread.sleep(100);



        //异步消息发送
//        producer.send(record, new Callback() {
//            @Override
//            public void onCompletion(RecordMetadata recordMetadata, Exception e) {
//                if(e != null){
//                    System.out.println("记录异常信息到日志表中");
//                }
//                System.out.println("异步发送返回结果 分区:"+recordMetadata.partition()+" topic"+recordMetadata.topic()+"   offset:"+recordMetadata.offset());
//            }
//        });

        //4.关闭消息通道，必须关闭，否则消息发送不成功
        producer.close();
    }

}